import {getDicItem, getEplid} from '../../api/api'
import {publicUrl} from '../../util/http'

function getWechatToken() {
  var c_name = 'wechat-token'
  var c_start;
  var c_end;
  if (document.cookie.length > 0) {
      var arr = document.cookie.split(/;\s*/g);
      for(var i = 0; i < arr.length; i++){
        var arr2=arr[i].split('=');
        if(c_name==arr2[0].trim()){
            if(arr2[1].trim().length > 10){
              return unescape(arr2[1]);
            }
        }
      }
      // let c_start = document.cookie.indexOf(c_name + "=")
      // if (c_start != -1) {
      //     c_start = c_start + c_name.length + 1;
      //     c_end = document.cookie.indexOf(";", c_start)
      //     if (c_end == -1) c_end = document.cookie.length
      //     return unescape(document.cookie.substring(c_start, c_end))
      // }
  }
  return undefined;
}

function getCookieValue(start, name) {

}
function clearCookies(){
//   let date=new Date();
//   date.setTime(date.getTime()-1000000);
//   let keys=document.cookie.match(/[^ =;]+(?=\=)/g);
//   if (keys) {
//     for (let i = keys.length; i--;) {
//       document.cookie=keys[i]+"=; expire="+date.toGMTString()+"; path=/";
//     }
//   }
//无需
}
const CommonUtil = {
    valid(container, target, field, tips) {
      if(target[field]) {
        return true;
      } else {
        container.$vux.alert.show({
          title: '提示',
          content: tips
        });
        return false;
      }
    },
    tryLogin(container) {
      return new Promise((resolve, reject) => {
        if(!container.$store.state.eid) {
          let descting = getWechatToken();
          // let confirm = window.confirm("请先登录系统..")
          if((!descting || descting.length<1) &&//
            (window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger')) {
            //通过正则表达式匹配ua中是否含有MicroMessenger字符串

            // if(confirm) {
              clearCookies();
              location.href = "https://open.auxgroup.com/oauth/oauth2url?appurl=" + window.location.href
              return;
            // }
          }
          getEplid({
            "decstring":descting
          }).then(res => {
            if (res && res.retCode === "000000") {
              console.log(res.retData);
              container.$store.state.eid = res.retData.emplId;
              container.$store.state.oprId = res.retData.oprId;
              container.$store.state.flag2 = res.retData.flag2; // 下属薪酬信息
              container.$store.state.bu = res.retData.bu;
            }
            resolve(res)
          });
        } else {
          resolve();
        }
      })

    },
    loadDic(target, fileName, value, key) {
      getDicItem( {
        fileName: fileName
      }).then(res => {
        res.retData.forEach((val) => {
        target.push({value: val[value], key: val[key]})
        });
      }).catch(res => {})
    },
    dateFtt(fmt,date) {
      var o = {
        "M+" : date.getMonth()+1,                 //月份
        "d+" : date.getDate(),                    //日
        "h+" : date.getHours(),                   //小时
        "m+" : date.getMinutes(),                 //分
        "s+" : date.getSeconds(),                 //秒
        "q+" : Math.floor((date.getMonth()+3)/3), //季度
        "S"  : date.getMilliseconds()             //毫秒
      };
      if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
      for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
      return fmt;
    },
    checkNumber(txt) {
      return /^([0-9])([0-9]|\.)*$/.test(txt)
    },
    checkPhone(phone) {
      return /^1[3-9]\d{9}$/.test(phone)
    },
    checkMail(mailAddr) {
      return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(mailAddr);
    },
    checkNationId(idStr) {
      return /(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(idStr)
    },
    getWechatToken:getWechatToken,
    fillDateEmpty(model, fields) {
      fields.forEach(d => {
        if(!model[d]){
          model[d] = '';
        }
      })
    },
    fillNumberEmpty(model, fields) {
      fields.forEach(d => {
        if(!model[d]){
          model[d] = '';
        }
      })
    },
    fillYNShow(model, fields) {
      fields.forEach(d => {
        model[d + "Value"] = model[d] == 'Y' ? '是' : (model[d] == 'N' ? '否' : '');
      })
    },
    updateFileUrl(models){
      if(models) {
        models.forEach(m => {
          m.fileUrl = publicUrl + m.attachsysfilename;
        })
      }

    },
    dateDiff(sDate1, sDate2) { //sDate1和sDate2是2017-9-25格式
        var aDate, oDate1, oDate2, iDays
        aDate = sDate1.split("-")
        oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为9-25-2017格式
        aDate = sDate2.split("-")
        oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
        iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数
        return iDays
    }
}
export default CommonUtil;
